package cn.seapon.talker.service;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import cn.seapon.talker.ChatActivity;
import cn.seapon.talker.FriendRequestReceiveActivity;
import cn.seapon.talker.R;
import cn.seapon.talker.bean.MessageEntity;
import cn.seapon.talker.common.ChatMsgEntity;
import cn.seapon.talker.common.FriendListInfomation.FriendInfomation;
import cn.seapon.talker.common.MessageGenre;
import cn.seapon.talker.common.TMessage;
import cn.seapon.talker.db.MessageEntityDao;
import cn.seapon.talker.infocarrier.SharedItems;
import cn.seapon.talker.net.SocketUtils;

/**
 * @author 作者 E-mail:
 * @version 创建时间：2015年1月3日 下午8:18:48 类说明
 */
public class MessageReceptionService extends Service {
	private static final String TAG = "__MessageReceptionService类";

	private static boolean hasRunning = false;
	private NotificationCompat.Builder mBuilder;
	private Bitmap icon;
	private MessageEntityDao messageEntityDao = new MessageEntityDao(getBaseContext());

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// 如果Socket不存在，跳转至登录界面
		if (SharedItems.socket == null) {
			// 停止服务
			stopSelf();
		}
		if (!hasRunning) {
			waitMessageFromServer();
		}
		super.onStart(intent, startId);
	}

	private void waitMessageFromServer() {
		new Thread() {

			@Override
			public void run() {
				while (true) {
					try {
						if ((SharedItems.socket == null)
								|| SharedItems.socket.isClosed()) {
							return;
						}
						String jsonString = SocketUtils
								.readStringFromSocket(SharedItems.socket);
						Log.d(TAG, "读取到" + jsonString);
						JSONObject jsonObject = new JSONObject(jsonString);
						TMessage tMessage = TMessage
								.getObjectFromJson(jsonObject);
						switch (tMessage.getGenre()) {
						case MessageGenre.CHAT_MESSAGE:// 接收到消息
							doWithChatMessage(tMessage);
							break;

						case MessageGenre.CHAT_SUCCESS:
							break;
						case MessageGenre.CHAT_FAILED:
							break;

						case MessageGenre.ADD_FRIEND_RESULT:
							Intent intent = new Intent();
							intent.putExtra("resultCode", tMessage.getContent()
									.getResultCode());
							intent.setAction("cn.seapon.talker.FRIEND_ADD_RESULT");// action与接收器相同
							sendBroadcast(intent);
							intent.setClass(getApplicationContext(),
									FriendRequestReceiveActivity.class);
							intent.putExtra("mesEntity",
									tMessage.getJSonString());
							startActivity(intent);
							break;
						default:
							break;
						}
					} catch (IOException e) {
						Log.i(TAG, "Socket异常");
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				// super.run();
			}

		}.start();

	}

	/**
	 * @获取默认的pendingIntent,为了防止2.3及以下版本报错
	 * @flags属性: 在顶部常驻:Notification.FLAG_ONGOING_EVENT 点击去除：
	 *           Notification.FLAG_AUTO_CANCEL
	 */
	public PendingIntent getDefalutIntent(int flags) {
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,
				new Intent(), flags);
		return pendingIntent;
	}

	private void doWithChatMessage(TMessage tMessage) {
		Log.e(TAG, tMessage.getJSonString());
		// 获取消息体显示到聊天列表中
		ChatMsgEntity chatMsgEntity = tMessage.getContent().getChatMsgEntity();
		String sender = chatMsgEntity.getSenderId();
		Intent intent = null;
		if (sender.equals(SharedItems.currentChat)) {
			// 正在跟当前用户聊天
			intent = new Intent();
			intent.putExtra("newChatMsgEntity", chatMsgEntity.getJSONString());
			Log.d(TAG, "加入的字符串是：" + chatMsgEntity.getJSONString());
			intent.setAction("cn.seapon.talker.CHAT_LIST_CHANGE");// action与接收器相同
			sendBroadcast(intent);
		} else {
			// 该消息的发送者不是当前聊天的对象 --> 发出通知
			notisfaction(chatMsgEntity);
		}

		// 作为聊天记录写入到数据库中
		messageEntityDao.add(MessageEntity.translateChatMsgEntityToMessageEntity(chatMsgEntity));
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	private void notisfaction(ChatMsgEntity chatMsgEntity) {
		String sender = chatMsgEntity.getSenderId();
		FriendInfomation friendInfo = SharedItems.friendListInfomation
				.getInfoById(sender);
		
		String nickname = friendInfo.getNickname();
		String remarkname = friendInfo.getRemarkname();
		String friendId = friendInfo.getId();
		String title = "";
		if (TextUtils.isEmpty(remarkname)) {
			if (TextUtils.isEmpty(nickname)) {
				title = friendId;
			} else {
				title = nickname;
			}
		} else {
			title = remarkname;
		}
		Intent resultIntent = new Intent(this, ChatActivity.class);
		resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		resultIntent.putExtra("friendEntity", friendInfo);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		doNotification(pendingIntent, chatMsgEntity.getContent(), title);
	}

	/**
	 * @param pendingIntent
	 * @param content
	 * @param title
	 */
	private void doNotification(PendingIntent pendingIntent, String content,
			String title) {
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		mBuilder = new NotificationCompat.Builder(this);
		mBuilder.setContentTitle(title)
				.setContentText(content)
				.setContentIntent(
						getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
				// .setNumber(number)//显示数量
				.setTicker(title + "  " + content)// 通知首次出现在通知栏，带上升动画效果的
				.setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
				// .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
				// .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
				.setOngoing(false)// ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
				.setDefaults(Notification.DEFAULT_VIBRATE)// 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
				// Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 //
				// requires VIBRATE permission
				.setSmallIcon(R.drawable.talker_logo);
		// Notification.FLAG_ONGOING_EVENT --设置常驻
		// Flag;Notification.FLAG_AUTO_CANCEL 通知栏上点击此通知后自动清除此通知
		// notification.flags = Notification.FLAG_AUTO_CANCEL;
		// //在通知栏上点击此通知后自动清除此通知
		mBuilder.setAutoCancel(true);
		// 点击后让通知将消失
		// 点击的意图ACTION是跳转到Intent
		mBuilder.setContentIntent(pendingIntent);
		mNotificationManager.notify(100, mBuilder.getNotification());
	}

}
